const DB = require('../tools/mongodb')
const responseEntity = require('../tools/responseEntity')

const api = {
  async getNickName(req, res) {
    const data = await DB.find('nickName', {
      isUsed: false
    })
    if (data.length === 0) {
      return responseEntity.setEneity({
        res,
        status: '500',
        message: '获取随机昵称失败'
      })
    }
    const result = data[Math.floor(Math.random() * data.length)]
    return responseEntity.setEneity({
      res,
      data: result.nickName
    })
  },
  // 判断nickName是否存在
  async isAlerady (nickName = '') {
    const data = await DB.find('nickName', {
      nickName
    })
    console.log(data.length > 0 && data[0].isUsed)
    if (data.length > 0 && data[0].isUsed) {
      return true
    }
    return false
  },
  async writeNickTag (nickName = '') {
    const data = await DB.find('nickName', {
      nickName
    })
    if (data.length === 0) {
      await DB.insertOne('nickName', {
        nickName,
        isUsed: true
      })
      return
    }
    DB.updateOne('nickName', {
      nickName
    }, {
      $set: { isUsed: true }
    })
  }
}

module.exports = api
